package cn.btks.resultintegration.catalog.service.impl;

import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.resultintegration.catalog.dto.CatalogDto;
import cn.btks.resultintegration.catalog.pojo.Catalog;
import cn.btks.resultintegration.catalog.repository.BaseCatalogRepository;
import cn.btks.resultintegration.catalog.repository.CatalogRepository;
import cn.btks.resultintegration.catalog.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author lijun
 * @Date 2020/12/14 17:17
 */
@Service
@Transactional
public class CatalogServiceImpl implements CatalogService {

    @Autowired
    CatalogRepository catalogRepository;

    @Autowired
    BaseCatalogRepository baseCatalogRepository;

    @Override
    public List<CatalogDto> findAll() {
        List<Catalog> catalogList = catalogRepository.findAll();
        List<Catalog> rootCatalog = new ArrayList<>();
        if (catalogList != null && catalogList.size() > 0) {
            for (Catalog item : catalogList) {
                if (item.getLevel() == 1) {
                    rootCatalog.add(item);
                }
            }
        }
        List<CatalogDto> catalogDtoList = new ArrayList<>();
        if (rootCatalog.size() > 0) {
            for (Catalog item : rootCatalog) {
                CatalogDto catalogDtos = recursion(item);
                catalogDtoList.add(catalogDtos);
            }
        }
        return catalogDtoList;
    }

    @Override
    public List<Catalog> findAll1() {
        return catalogRepository.findAll();
    }

    @Override
    public Catalog findById(Long id) {
        Optional<Catalog> optional = catalogRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    @Override
    public Catalog findByCode(String code) {
        return catalogRepository.findByCode(code);
    }

    @Override
    public Catalog findByKeyCode(String keyCode) {
        return catalogRepository.findByKeyCode(keyCode);
    }

    @Override
    public Catalog findLikeKeyCode(String keyCode) {
        return catalogRepository.findLikeKeyCode(keyCode);
    }

    @Override
    public List<Catalog> findAllByUpLevelId(Long upLevelId) {
        return catalogRepository.findAllByUpLevelId(upLevelId);
    }

    @Override
    public List<Long> findAllCatalogIdById(Long id) {
        List<Long> idList = new ArrayList<>();
        Optional<Catalog> optional = catalogRepository.findById(id);
        if(optional.isPresent()){
            Catalog catalog = optional.get();
            idList = recursion(catalog, idList);
        }
        return idList;
    }

    @Override
    public ResultState save(Catalog catalog) {
//        Integer level = catalog.getLevel();
//        Integer maxOrder = catalogRepository.findByMaxOrder(catalog.getLevel(), catalog.getUpLevelId());
//        if(maxOrder == null){
//            maxOrder = 1;
//        }
//        Catalog catalog2 = catalogRepository.findByLevelAndUpLevelIdAndCatalogOrder(catalog.getLevel(), catalog.getUpLevelId(), Long.valueOf(maxOrder));
//        if (catalog2 != null) {
//            String code = catalog2.getCode();
//            long codeLong = Long.valueOf(code);
//            maxOrder++;
//            codeLong++;//未做123级时，order大于9处理，暂时认为不能超过九
//            catalog.setCode(String.valueOf(codeLong));
//            catalog.setCatalogOrder(Long.valueOf(maxOrder));
//        } else { //当不存在子节点时
//            Optional<Catalog> optional = catalogRepository.findById(catalog.getUpLevelId());
//            if(optional.isPresent()){
//                String code = optional.get().getCode();
//                String codeFinal = code + String.valueOf(maxOrder);
//                catalog.setCode(codeFinal);
//                catalog.setCatalogOrder(Long.valueOf(maxOrder));
//            }
//        }

        Catalog catalog1 = catalogRepository.save(catalog);
        return catalog1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), catalog1) :
                new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState saveAll(List<Catalog> catalogList) {
        if (catalogList != null && catalogList.size() > 0) {
            for (Catalog item : catalogList) {
                Integer level = item.getLevel();
                int maxOrder = catalogRepository.findByMaxOrder(item.getLevel(), item.getUpLevelId());
                Catalog catalog2 = catalogRepository.findByLevelAndUpLevelIdAndCatalogOrder(item.getLevel(), item.getUpLevelId(), Long.valueOf(maxOrder));
                if (catalog2 != null) {
                    String code = catalog2.getCode();
                    long codeLong = Long.valueOf(code);
                    maxOrder++;
                    codeLong++;//未做123级时，order大于9处理，暂时认为不能超过九
                    item.setCode(String.valueOf(codeLong));
                    item.setCatalogOrder(Long.valueOf(maxOrder));
                }
            }
        }
        baseCatalogRepository.insertCatalogs(catalogList);
        return new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg());
    }

    @Override
    public ResultState update(Catalog catalog) {
        if (catalog.getId() != null) {
            Catalog catalog1 = catalogRepository.save(catalog);
            return catalog1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), catalog1) :
                    new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
        }
        return new ResultState(StateInfo.SAVE_ERROR1.getCode(), StateInfo.SAVE_ERROR1.getMsg());
    }

    @Override
    public ResultState updateAll(List<Catalog> catalogList) {
        List<Catalog> updateCatalogList = new ArrayList<>();
        for (Catalog item : catalogList) {
            if (item.getId() != null) {
                updateCatalogList.add(item);
            }
        }
        if (updateCatalogList.size() == catalogList.size()) {
            baseCatalogRepository.updateCatalogs(updateCatalogList);
            return new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg());
        } else {
            return new ResultState(StateInfo.SAVE_ERROR2.getCode(), StateInfo.SAVE_ERROR2.getMsg());
        }
    }

    @Override
    public ResultState delete(Long id) {
        Optional<Catalog> optional = catalogRepository.findById(id);
        if (optional.isPresent()) {
            // TODO: 2020/12/15 判断是否目录下存在成果数据
            int result = catalogRepository.deleteByCode(optional.get().getCode());
            return result > 0 ? new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg()) :
                    new ResultState(StateInfo.DELETE_ERROR_2.getCode(), StateInfo.DELETE_ERROR_2.getMsg());
        }
        return new ResultState(StateInfo.DELETE_ERROR_2.getCode(), StateInfo.DELETE_ERROR_2.getMsg());
    }

    /**
     * 递归查询目录
     *
     * @param catalog
     * @return
     */
    private CatalogDto recursion(Catalog catalog) {
        CatalogDto catalogDto = new CatalogDto();
        catalogDto.setParent(catalog);
        List<CatalogDto> children = new ArrayList<>();
        catalogDto.setChildren(children);
        Long id = catalog.getId();
        List<Catalog> catalogList = catalogRepository.findAllByUpLevelId(id);
        if (catalogList != null && catalogList.size() > 0) {
            for (Catalog item : catalogList) {
                CatalogDto childrenItem = recursion(item);
                children.add(childrenItem);
            }
        }
        return catalogDto;
    }

    /**
     * 递归查询目录ID
     *
     * @param catalog
     * @return
     */
    private List<Long> recursion(Catalog catalog,List<Long> idList) {
        Long id = catalog.getId();
        idList.add(id);
        List<Catalog> catalogList = catalogRepository.findAllByUpLevelId(id);
        if (catalogList != null && catalogList.size() > 0) {
            for (Catalog item : catalogList) {
                idList = recursion(item,idList);
            }
        }
        return idList;
    }

}
